package com.chhuang.ewcrm.thread;

import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.comm.CommStartListener;
import com.chhuang.ewcrm.comm.CommWeighValue;
import com.chhuang.ewcrm.comm.Serial;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WWeighMeterDao;
import com.chhuang.ewcrm.entity.WWeighMeter;
import com.chhuang.ewcrm.utils.MyAlert;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import javafx.scene.control.Label;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.TooManyListenersException;
import static javafx.application.Platform.runLater;

/**
 * 过磅仪表串口通讯线程
 * @author chhuang
 * @create 2020-10-13-9:41
 */
public class InitWeighCommThread implements Runnable{
    private final Logger logger = LoggerFactory.getLogger(InitWeighCommThread.class);

    private CommStartListener weighCommStartListener;//监听过磅仪表

    private final Label weighLEDLabel;

    private WWeighMeterDao wWeighMeterDao = App.getSession().getMapper(WWeighMeterDao.class);

    public InitWeighCommThread(Label weighLEDLabel){
        this.weighLEDLabel = weighLEDLabel;
    }

    @Override
    public void run() {
        try {
            //监听过磅仪表
            //获取配置信息，串口名称，波特率，数据位，停止位，效验位
            WWeighMeter wWeighMeter = wWeighMeterDao.queryById("001");
            if(wWeighMeter!=null && wWeighMeter.getWmeterEnable()){
                weighCommStartListener = new CommStartListener(
                        new Serial(wWeighMeter.getWmeterComm(),
                                wWeighMeter.getWmeterBaudrate(),
                                wWeighMeter.getWmeterDatabits(),
                                wWeighMeter.getWmeterStopbits(),
                                wWeighMeter.getWmeterParity()),
                        new CommWeighValue(weighLEDLabel));
            }
        } catch (PortInUseException | IOException | NoSuchPortException | TooManyListenersException | UnsupportedCommOperationException e) {
            runLater(()->weighLEDLabel.setText(Constants.NO_SIGN_STR));
            e.printStackTrace();
            MyAlert.showErrorLater("错误",null, "打开串口出错，请查看串口配置信息是否有误。");
        }
    }

    /**
     * 关闭串口连接
     */
    public void close(){
        if(weighCommStartListener!=null)
            weighCommStartListener.close();
    }
}
